// EStoreServer.java
package com.estore.network;

import com.estore.service.ProductService;
import com.estore.model.Product;    
import com.estore.model.Order;
import com.estore.model.OrderService;
import com.estore.service.UserService;
import com.estore.model.User;

import java.io.*;
import java.net.*;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class EStoreServer {
    private static final int PORT = 8888;
    private static String[] args;
    private final ProductService productService;
    private final OrderService orderService;
    private final UserService userService;
    private final ScheduledExecutorService scheduler;

    public EStoreServer() {
        System.out.println("初始化ProductService...");
        this.productService = new ProductService();
        System.out.println("初始化OrderService...");
        this.orderService = new OrderService(productService);
        System.out.println("初始化UserService...");
        this.userService = new UserService();
        System.out.println("加载订单数据...");
        // 加载已存在的订单数据
        this.orderService.loadData();
        
        // 初始化定时任务调度器
        this.scheduler = Executors.newScheduledThreadPool(1);
        
        // 启动定期清理过期订单的任务（每5分钟执行一次）
        startExpiredOrderCleanupTask();
        
        System.out.println("EStoreServer初始化完成");
    }

    public static void main(String[] args) {
        EStoreServer.args = args;
        System.out.println("正在启动EStore服务器...");
        EStoreServer server = new EStoreServer();
        System.out.println("服务器初始化完成，开始监听...");
        server.start();
    }

    public static String[] getArgs() {
        return args;
    }

   public void start() {
    try (ServerSocket serverSocket = new ServerSocket(PORT)) {
        System.out.printf("服务器启动，监听端口: %d%n", PORT);

        while (true) {
            try {
                Socket clientSocket = serverSocket.accept();
                System.out.printf("客户端连接: %s%n", clientSocket.getInetAddress());
                handleClient(clientSocket);
            } catch (IOException e) {
                // Check if caused by thread interruption
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println("服务器被中断，正在关闭...");
                    break;
                }
                System.err.printf("处理客户端连接时出错: %s%n", e.getMessage());
            }
        }
    } catch (IOException e) {
        System.err.printf("服务器启动失败: %s%n", e.getMessage());
    }
}

    private void handleClient(Socket clientSocket) {
        try (ObjectInputStream input = new ObjectInputStream(clientSocket.getInputStream());
             ObjectOutputStream output = new ObjectOutputStream(clientSocket.getOutputStream())) {

            // 读取客户端请求
            String request = (String) input.readObject();
            System.out.printf("收到客户端请求: %s%n", request);

            // 根据请求处理业务逻辑
            if ("GET ALL PRODUCTS".equals(request)) {
                List<Product> products = productService.getAllProducts();
                output.writeObject(products);
                output.flush();
            } else if (request.startsWith("CREATE ORDER")) {
                // 处理创建订单请求
                // 请求格式: "CREATE ORDER:userId:item1,qty1;item2,qty2;..."
                String[] parts = request.split(":", 3);
                if (parts.length >= 3) {
                    String userId = parts[1];
                    String itemsStr = parts[2];
                    
                    // 解析商品项目
                    String[] itemPairs = itemsStr.split(";");
                    java.util.Map<String, Integer> items = new java.util.HashMap<>();
                    for (String itemPair : itemPairs) {
                        String[] itemParts = itemPair.split(",");
                        if (itemParts.length == 2) {
                            try {
                                items.put(itemParts[0], Integer.parseInt(itemParts[1]));
                            } catch (NumberFormatException e) {
                                System.err.printf("解析商品数量时出错: %s%n", itemParts[1]);
                                output.writeObject("商品数量格式错误: %s".formatted(itemParts[1]));
                                output.flush();
                                return;
                            }
                        } else {
                            System.err.printf("商品项格式错误: %s%n", itemPair);
                            output.writeObject("商品项格式错误: %s".formatted(itemPair));
                            output.flush();
                            return;
                        }
                    }
                    
                    // 创建订单
                    try {
                        Order order = orderService.createOrder(userId, items);
                        output.writeObject(order);
                        output.flush();
                    } catch (Exception e) {
                        System.err.printf("创建订单失败: %s%n", e.getMessage());
                        output.writeObject("订单创建失败: %s".formatted(e.getMessage()));
                        output.flush();
                    }
                } else {
                    System.err.printf("订单参数错误: 请求格式不正确 - %s%n", request);
                    output.writeObject("订单参数错误: 请求格式应为 CREATE ORDER:userId:item1,qty1;item2,qty2;...");
                    output.flush();
                }
            } else if (request.startsWith("UPDATE PRODUCT")) {
       // 处理商品信息更新请求
       // 请求格式: "UPDATE PRODUCT:productId:field:newValue"
       String[] parts = request.split(":", 4);
       if (parts.length >= 4) {
           String productId = parts[1];
           String field = parts[2];
           String newValue = parts[3];

           try {
               Product product = productService.findProductById(productId);
               if (product != null) {
                   switch (field) {
                       case "name":
                           product.setName(newValue);
                           break;
                       case "price":
                           product.setPrice(Double.parseDouble(newValue));
                           break;
                       case "stock":
                           product.setStock(Integer.parseInt(newValue));
                           break;
                       default:
                           output.writeObject("不支持的字段: %s".formatted(field));
                           output.flush();
                           return;
                   }
                   productService.saveData(); // 保存数据
                   output.writeObject(product);
               } else {
                   output.writeObject("商品不存在");
               }
           } catch (Exception e) {
               output.writeObject("更新失败: %s".formatted(e.getMessage()));
           }
           output.flush();
       } else {
           output.writeObject("参数错误");
           output.flush();
       }
   } else if (request.startsWith("UPDATE ORDER STATUS")) {
                // 更新订单状态
                // 请求格式: "UPDATE ORDER STATUS:orderId:status"
                String[] parts = request.split(":", 3);
                if (parts.length >= 3) {
                    String orderId = parts[1];
                    String statusStr = parts[2];
                    
                    try {
                        Order.OrderStatus status = Order.OrderStatus.valueOf(statusStr);
                        Order updatedOrder = orderService.updateOrderStatus(orderId, status);
                        output.writeObject(Objects.requireNonNullElse(updatedOrder, "订单不存在"));
                    } catch (IllegalArgumentException e) {
                        output.writeObject("无效的订单状态: %s".formatted(statusStr));
                    } catch (RuntimeException e) {
                        System.err.printf("订单状态更新失败: %s%n", e.getMessage());
                        output.writeObject("订单状态更新失败: %s".formatted(e.getMessage()));
                    }
                    output.flush();
                } else {
                    System.err.printf("订单状态更新参数错误: 请求格式不正确 - %s%n", request);
                    output.writeObject("订单状态更新参数错误: 请求格式应为 UPDATE ORDER STATUS:orderId:status");
                    output.flush();
                }
            } else if (request.startsWith("GET ORDERS BY USER")) {
                // 获取用户订单
                String[] parts = request.split(":");
                if (parts.length >= 2) {
                    String userId = parts[1];
                    try {
                        List<Order> orders = orderService.getOrdersByUserId(userId);
                        output.writeObject(orders);
                    } catch (Exception e) {
                        System.err.printf("获取用户订单失败: %s%n", e.getMessage());
                        output.writeObject("获取用户订单失败: %s".formatted(e.getMessage()));
                    }
                    output.flush();
                } else {
                    System.err.printf("用户ID参数缺失: 请求格式不正确 - %s%n", request);
                    output.writeObject("用户ID参数缺失: 请求格式应为 GET ORDERS BY USER:userId");
                    output.flush();
                }
            } else if (request.equals("GET ALL ORDERS")) {
                // 获取所有订单（管理员功能）
                try {
                    List<Order> allOrders = orderService.getAllOrders();
                    output.writeObject(allOrders);
                } catch (Exception e) {
                    System.err.printf("获取所有订单失败: %s%n", e.getMessage());
                    output.writeObject("获取所有订单失败: %s".formatted(e.getMessage()));
                }
                output.flush();
            } else if (request.startsWith("USER LOGIN")) {
                // 处理用户登录请求
                // 请求格式: "USER LOGIN:username:password"
                String[] parts = request.split(":", 3);
                if (parts.length >= 3) {
                    String username = parts[1];
                    String password = parts[2];
                    
                    User user = userService.login(username, password);
                    output.writeObject(Objects.requireNonNullElse(user, "登录失败：用户名或密码错误"));
                } else {
                    output.writeObject("登录参数错误");
                }
                output.flush();
            } else if (request.startsWith("USER REGISTER")) {
                // 处理用户注册请求
                // 请求格式: "USER REGISTER:username:password:email"
                String[] parts = request.split(":", 4);
                if (parts.length >= 4) {
                    String username = parts[1];
                    String password = parts[2];
                    String email = parts[3];
                    
                    try {
                        User user = userService.register(username, password, email);
                        output.writeObject(user);
                    } catch (IllegalArgumentException e) {
                        output.writeObject("注册失败: %s".formatted(e.getMessage()));
                    }
                } else {
                    output.writeObject("注册参数错误");
                }
                output.flush();
            } else if (request.startsWith("UPDATE USER INFO")) {
                // 处理更新用户信息请求
                // 请求格式: "UPDATE USER INFO:userId:email:phone:address"
                String[] parts = request.split(":", 5);
                if (parts.length >= 5) {
                    String userId = parts[1];
                    String email = parts[2];
                    String phone = parts[3];
                    String address = parts[4];
                    
                    User user = userService.updateUserInfo(userId, email, phone, address);
                    output.writeObject(Objects.requireNonNullElse(user, "更新失败：用户不存在"));
                } else {
                    output.writeObject("更新参数错误");
                }
                output.flush();
            } else if (request.startsWith("CHANGE PASSWORD")) {
                // 处理修改密码请求
                // 请求格式: "CHANGE PASSWORD:userId:oldPassword:newPassword"
                String[] parts = request.split(":", 4);
                if (parts.length >= 4) {
                    String userId = parts[1];
                    String oldPassword = parts[2];
                    String newPassword = parts[3];
                    
                    boolean success = userService.changePassword(userId, oldPassword, newPassword);
                    if (success) {
                        output.writeObject("密码修改成功");
                    } else {
                        output.writeObject("密码修改失败：原密码不正确或用户不存在");
                    }
                } else {
                    output.writeObject("修改密码参数错误");
                }
                output.flush();
            } else if (request.startsWith("GET ALL USERS")) {
                // 获取所有用户（管理员功能）
                try {
                    List<User> users = userService.getAllUsers();
                    output.writeObject(users);
                } catch (Exception e) {
                    System.err.printf("获取所有用户失败: %s%n", e.getMessage());
                    output.writeObject("获取所有用户失败: %s".formatted(e.getMessage()));
                }
                output.flush();
            } else if (request.startsWith("DELETE USER")) {
                // 处理删除用户请求
                // 请求格式: "DELETE USER:userId"
                String[] parts = request.split(":", 2);
                if (parts.length >= 2) {
                    String userId = parts[1];
                    
                    boolean success = userService.deleteUser(userId);
                    if (success) {
                        output.writeObject("用户删除成功");
                    } else {
                        output.writeObject("用户删除失败：用户不存在或不能删除管理员账户");
                    }
                } else {
                    output.writeObject("删除用户参数错误");
                }
                output.flush();
            } else if (request.startsWith("RESET USER PASSWORD")) {
    // 重置指定用户密码为"123"
    // 请求格式: "RESET USER PASSWORD:userId"
    String[] parts = request.split(":", 3);
    if (parts.length >= 2) {
        String userId = parts[1];

        try {
            boolean success = userService.resetUserPassword(userId, "123");
            if (success) {
                output.writeObject("用户密码已重置为123");
            } else {
                output.writeObject("用户不存在，密码重置失败");
            }
        } catch (Exception e) {
            System.err.printf("重置用户密码失败: %s%n", e.getMessage());
            output.writeObject("重置用户密码失败: %s".formatted(e.getMessage()));
        }
        output.flush();
    } else {
        output.writeObject("重置用户密码参数错误");
        output.flush();
    }
}
else if (request.startsWith("UPDATE USER ROLE")) {
                // 处理更新用户角色请求
                // 请求格式: "UPDATE USER ROLE:userId:role"
                String[] parts = request.split(":", 3);
                if (parts.length >= 3) {
                    String userId = parts[1];
                    String roleStr = parts[2];
                    
                    try {
                        User.UserRole role = User.UserRole.valueOf(roleStr);
                        boolean success = userService.updateUserRole(userId, role);
                        if (success) {
                            output.writeObject("用户角色更新成功");
                        } else {
                            output.writeObject("用户角色更新失败：用户不存在");
                        }
                    } catch (IllegalArgumentException e) {
                        output.writeObject("无效的用户角色: %s".formatted(roleStr));
                    }
                } else {
                    output.writeObject("更新用户角色参数错误");
                }
                output.flush();
            } else if (request.startsWith("UPDATE USER POINTS")) {
                // 处理更新用户积分请求
                // 请求格式: "UPDATE USER POINTS:userId:points"
                String[] parts = request.split(":", 3);
                if (parts.length >= 3) {
                    String userId = parts[1];
                    int points;
                    try {
                        points = Integer.parseInt(parts[2]);
                    } catch (NumberFormatException e) {
                        output.writeObject("积分格式错误");
                        output.flush();
                        return;
                    }
                    
                    User user = userService.updatePoints(userId, points);
                    output.writeObject(Objects.requireNonNullElse(user, "积分更新失败：用户不存在"));
                } else {
                    output.writeObject("更新积分参数错误");
                }
                output.flush();
            } else if (request.startsWith("FIND USER BY ID")) {
                // 处理查找用户请求
                // 请求格式: "FIND USER BY ID:userId"
                String[] parts = request.split(":", 2);
                if (parts.length >= 2) {
                    String userId = parts[1];
                    
                    User user = userService.findUserById(userId);
                    output.writeObject(Objects.requireNonNullElse(user, "用户不存在"));
                } else {
                    output.writeObject("查找用户参数错误");
                }
                output.flush();
            } else if (request.startsWith("UNLOCK USER")) {
                // 处理解锁用户账户请求
                // 请求格式: "UNLOCK USER:userId"
                String[] parts = request.split(":", 2);
                if (parts.length >= 2) {
                    String userId = parts[1];
                    
                    boolean success = userService.unlockUser(userId);
                    if (success) {
                        output.writeObject("用户账户解锁成功");
                    } else {
                        output.writeObject("用户账户解锁失败：用户不存在");
                    }
                } else {
                    output.writeObject("解锁用户参数错误");
                }
                output.flush();
            } else if (request.startsWith("DEDUCT POINTS")) {
                // 处理扣除积分请求
                // 请求格式: "DEDUCT POINTS:userId:amount"
                String[] parts = request.split(":", 3);
                if (parts.length >= 3) {
                    String userId = parts[1];
                    double amount;
                    try {
                        amount = Double.parseDouble(parts[2]);
                    } catch (NumberFormatException e) {
                        output.writeObject("金额格式错误");
                        output.flush();
                        return;
                    }
                    
                    User user = userService.deductPointsByAmount(userId, amount);
                    output.writeObject(Objects.requireNonNullElse(user, "积分扣除失败：用户不存在"));
                } else {
                    output.writeObject("扣除积分参数错误");
                }
                output.flush();
            } else if (request.startsWith("ADD POINTS")) {
                // 处理增加积分请求
                // 请求格式: "ADD POINTS:userId:amount"
                String[] parts = request.split(":", 3);
                if (parts.length >= 3) {
                    String userId = parts[1];
                    double amount;
                    try {
                        amount = Double.parseDouble(parts[2]);
                    } catch (NumberFormatException e) {
                        output.writeObject("金额格式错误");
                        output.flush();
                        return;
                    }
                    
                  User user = userService.addPointsByAmount(userId, amount);
if (user != null) {
    output.writeObject(user);
} else {
    output.writeObject("积分增加失败：用户不存在");
}

                } else {
                    output.writeObject("增加积分参数错误");
                }
                output.flush();
            } else if (request.startsWith("ADD TAG TO PRODUCT")) {
                // 处理添加商品标签请求
                // 请求格式: "ADD TAG TO PRODUCT:productId:tag"
                String[] parts = request.split(":", 3);
                if (parts.length >= 3) {
                    String productId = parts[1];
                    String tag = parts[2];
                    
                    boolean success = productService.addTagToProduct(productId, tag);
                    if (success) {
                        output.writeObject("标签添加成功");
                    } else {
                        output.writeObject("标签添加失败：商品不存在或标签已存在");
                    }
                } else {
                    output.writeObject("添加标签参数错误");
                }
                output.flush();
            } else if (request.startsWith("REMOVE TAG FROM PRODUCT")) {
                // 处理移除商品标签请求
                // 请求格式: "REMOVE TAG FROM PRODUCT:productId:tag"
                String[] parts = request.split(":", 3);
                if (parts.length >= 3) {
                    String productId = parts[1];
                    String tag = parts[2];
                    
                    boolean success = productService.removeTagFromProduct(productId, tag);
                    if (success) {
                        output.writeObject("标签移除成功");
                    } else {
                        output.writeObject("标签移除失败：商品不存在或标签不存在");
                    }
                } else {
                    output.writeObject("移除标签参数错误");
                }
                output.flush();
            } else if (request.startsWith("UPDATE PRODUCT TAGS")) {
                // 处理更新商品标签请求
                // 请求格式: "UPDATE PRODUCT TAGS:productId:tag1,tag2,tag3,..."
                String[] parts = request.split(":", 3);
                if (parts.length >= 3) {
                    String productId = parts[1];
                    String tagsStr = parts[2];
                    
                    // 解析标签
                    Set<String> tags = new java.util.HashSet<>();
                    if (!tagsStr.isEmpty()) {
                        String[] tagArray = tagsStr.split(",");
                        for (String tag : tagArray) {
                            String trimmedTag = tag.trim();
                            if (!trimmedTag.isEmpty()) {
                                tags.add(trimmedTag);
                            }
                        }
                    }
                    
                    Product product = productService.updateTags(productId, tags);
                    output.writeObject(Objects.requireNonNullElse(product, "标签更新失败：商品不存在"));
                } else {
                    output.writeObject("更新标签参数错误");
                }
                output.flush();
            } else if (request.startsWith("GENERATE SALES REPORT")) {
                // 处理生成销售报告请求
                // 请求格式: "GENERATE SALES REPORT:startDate:endDate"
                String[] parts = request.split(":", 3);
                if (parts.length >= 3) {
                    try {
                        java.time.LocalDate startDate = java.time.LocalDate.parse(parts[1]);
                        java.time.LocalDate endDate = java.time.LocalDate.parse(parts[2]);

                        // 初始化ReportService
                        com.estore.service.ReportService reportService = new com.estore.service.ReportService(orderService, productService, userService);
                        com.estore.service.ReportService.SalesReport report = reportService.generateSalesReport(startDate, endDate);

                        output.writeObject(report);
                    } catch (Exception e) {
                        System.err.printf("生成销售报告失败: %s%n", e.getMessage());
                        output.writeObject("生成销售报告失败: %s".formatted(e.getMessage()));
                    }
                } else {
                    output.writeObject("生成销售报告参数错误");
                }
                output.flush();
            } else if (request.startsWith("GENERATE USER BEHAVIOR ANALYSIS")) {
                // 处理生成用户行为分析报告请求
                // 请求格式: "GENERATE USER BEHAVIOR ANALYSIS:startDate:endDate"
                String[] parts = request.split(":", 3);
                if (parts.length >= 3) {
                    try {
                        java.time.LocalDate startDate = java.time.LocalDate.parse(parts[1]);
                        java.time.LocalDate endDate = java.time.LocalDate.parse(parts[2]);
                        
                        // 初始化ReportService
                        com.estore.service.ReportService reportService = new com.estore.service.ReportService(orderService, productService, userService);
                        com.estore.service.ReportService.UserBehaviorAnalysis analysis = reportService.generateUserBehaviorAnalysis(startDate, endDate);
                        
                        output.writeObject(analysis);
                    } catch (Exception e) {
                        System.err.printf("生成用户行为分析报告失败: %s%n", e.getMessage());
                        output.writeObject("生成用户行为分析报告失败: %s".formatted(e.getMessage()));
                    }
                } else {
                    output.writeObject("生成用户行为分析报告参数错误");
                }
                output.flush();
            } else if (request.startsWith("GENERATE PRODUCT RANKING")) {
                // 处理生成商品销售排行榜请求
                // 请求格式: "GENERATE PRODUCT RANKING:limit:startDate:endDate"
                String[] parts = request.split(":", 4);
                if (parts.length >= 4) {
                    try {
                        int limit = Integer.parseInt(parts[1]);
                        java.time.LocalDate startDate = java.time.LocalDate.parse(parts[2]);
                        java.time.LocalDate endDate = java.time.LocalDate.parse(parts[3]);
                        
                        // 初始化ReportService
                        com.estore.service.ReportService reportService = new com.estore.service.ReportService(orderService, productService, userService);
                        java.util.List<com.estore.service.ReportService.ProductRanking> rankings = reportService.getProductSalesRanking(limit, startDate, endDate);
                        
                        output.writeObject(rankings);
                    } catch (Exception e) {
                        System.err.printf("生成商品销售排行榜失败: %s%n", e.getMessage());
                        output.writeObject("生成商品销售排行榜失败: %s".formatted(e.getMessage()));
                    }
                } else {
                    output.writeObject("生成商品销售排行榜参数错误");
                }
                output.flush();
            } else if (request.startsWith("GENERATE FINANCIAL REPORT")) {
                // 处理生成财务报表请求
                // 请求格式: "GENERATE FINANCIAL REPORT:startDate:endDate"
                String[] parts = request.split(":", 3);
                if (parts.length >= 3) {
                    try {
                        java.time.LocalDate startDate = java.time.LocalDate.parse(parts[1]);
                        java.time.LocalDate endDate = java.time.LocalDate.parse(parts[2]);
                        
                        // 初始化ReportService
                        com.estore.service.ReportService reportService = new com.estore.service.ReportService(orderService, productService, userService);
                        com.estore.service.ReportService.FinancialReport report = reportService.generateFinancialReport(startDate, endDate);
                        
                        output.writeObject(report);
                    } catch (Exception e) {
                        System.err.printf("生成财务报表失败: %s%n", e.getMessage());
                        output.writeObject("生成财务报表失败: %s".formatted(e.getMessage()));
                    }
                } else {
                    output.writeObject("生成财务报表参数错误");
                }
                output.flush();
            } else if (request.startsWith("CHECK ORDER EXPIRED")) {
                // 检查订单是否过期
                // 请求格式: "CHECK ORDER EXPIRED:orderId"
                String[] parts = request.split(":", 2);
                if (parts.length >= 2) {
                    String orderId = parts[1];
                    boolean isExpired = orderService.isOrderExpired(orderId);
                    long remainingMinutes = orderService.getOrderRemainingMinutes(orderId);
                    
                    String response;
                    if (isExpired) {
                        response = "订单已过期";
                    } else if (remainingMinutes >= 0) {
                        response = "订单剩余有效时间: %d 分钟".formatted(remainingMinutes);
                    } else {
                        response = "订单不存在或不是待付款状态";
                    }
                    
                    output.writeObject(response);
                } else {
                    output.writeObject("检查订单过期参数错误");
                }
                output.flush();
            } else if (request.equals("CLEANUP EXPIRED ORDERS")) {
                // 手动清理过期订单
                try {
                    int cleanedCount = orderService.cleanupExpiredOrders();
                    output.writeObject("已清理 %d 个过期订单".formatted(cleanedCount));
                } catch (Exception e) {
                    output.writeObject("清理过期订单失败: %s".formatted(e.getMessage()));
                }
                output.flush();
            } else if (request.equals("GET ORDERS ABOUT TO EXPIRE")) {
                // 获取即将过期的订单
                try {
                    List<Order> aboutToExpire = orderService.getOrdersAboutToExpire();
                    output.writeObject(aboutToExpire);
                } catch (Exception e) {
                    output.writeObject("获取即将过期订单失败: %s".formatted(e.getMessage()));
                }
                output.flush();
            } else {
                output.writeObject("未知请求");
                output.flush();
            }
        } catch (IOException | ClassNotFoundException e) {
            System.err.printf("处理客户端请求时出错: %s%n", e.getMessage());
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                System.err.printf("关闭客户端连接时出错: %s%n", e.getMessage());
            }
        }
    }

    /**
     * 启动定期清理过期订单的任务
     */
    private void startExpiredOrderCleanupTask() {
        scheduler.scheduleAtFixedRate(() -> {
            try {
                int cleanedCount = orderService.cleanupExpiredOrders();
                if (cleanedCount > 0) {
                    System.out.printf("[定时任务] 清理了 %d 个过期订单%n", cleanedCount);
                }
                
                // 检查即将过期的订单
                List<Order> aboutToExpire = orderService.getOrdersAboutToExpire();
                if (!aboutToExpire.isEmpty()) {
                    System.out.printf("[提醒] 有 %d 个订单即将在5分钟内过期：%n", aboutToExpire.size());
                    for (Order order : aboutToExpire) {
                        long remainingMinutes = orderService.getOrderRemainingMinutes(order.getOrderId());
                        System.out.printf("  - 订单 %s，剩余 %d 分钟%n", order.getOrderId(), remainingMinutes);
                    }
                }
            } catch (Exception e) {
                System.err.printf("[定时任务] 清理过期订单时出错: %s%n", e.getMessage());
            }
        }, 5, 5, TimeUnit.MINUTES); // 初始延迟5分钟，然后每5分钟执行一次
        
        System.out.println("[定时任务] 过期订单清理任务已启动（每5分钟执行一次）");
    }

}